import pymysql
import logging
from config import MYSQL_CONFIG


class DBUtil():
    conn = None

    @classmethod
    def get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host=MYSQL_CONFIG.get("host"), port=MYSQL_CONFIG.get("port"),
                                       user=MYSQL_CONFIG.get("username"), password=MYSQL_CONFIG.get("password"),
                                       database=MYSQL_CONFIG.get("database"), charset='utf8')
            logging.info("数据库连接创建成功")
        return cls.conn

    @classmethod
    def close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
        cls.conn = None

    @classmethod
    def select_one(cls, sql):
        """查询一条"""
        cursor = None
        result = None
        try:
            # 创建游标
            cursor = cls.get_conn().cursor()
            # 执行sql
            cursor.execute(sql)
            # 提取一条结果集
            result = cursor.fetchone()
        except Exception as err:
            print(f'查询异常: {err}')
            logging.info(f"查询异常{err}")
        finally:
            # 关闭游标和连接
            cursor.close()
            cls.close_conn()
        # 返回结果集
        return result

    @classmethod
    def uid_db(cls, sql):
        """增删改方法"""
        cursor = None
        row_num = None
        conn = None
        try:
            # 获取连接
            conn = cls.get_conn()
            # 创建游标
            cursor = conn.cursor()
            # 执行sql
            cursor.execute(sql)
            # 获取受影响的行数
            row_num = conn.affected_rows()
            # 事务提交
            conn.commit()
        except Exception as err:
            # 事务回滚
            conn.rollback()
            print(f"增删改sql执行异常: {err}")
            logging.info(f"增删改sql执行异常{err}")
        finally:
            # 关闭游标和连接
            cursor.close()
            cls.close_conn()
        return row_num


if __name__ == '__main__':
    res = DBUtil.select_one("select * from `user` WHERE id = '100287'")
    print(res)